package com.xigege.netty.nettyComponent.futureAndPromise;

import io.netty.channel.EventLoop;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.util.concurrent.DefaultPromise;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;


import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

public class TestNettyPromise {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        EventLoop eventLoop = new NioEventLoopGroup(1).next();
        // 传入一个EventLoop事件, 手动创建一个结果容器
        DefaultPromise<Integer> promise = new DefaultPromise<>(eventLoop);

        // 任意一个线程计算结果,并且往 promise 中填充结果
        new Thread(()->{
            try {
//                int i= 1/0;
                System.out.println(Thread.currentThread().getName() + "开始计算...");
                TimeUnit.SECONDS.sleep(2);
                // 填充成功结果
                promise.setSuccess(12332112);
                System.out.println(Thread.currentThread().getName() + "计算完成");
            } catch (InterruptedException e) {
                // 可填充失败结果
                promise.setFailure(e);
                throw new RuntimeException(e);
            }
        }).start();

        // 同步获取promise结果
        System.out.println(Thread.currentThread().getName() + "等待计算结果");
        System.out.println(Thread.currentThread().getName() + "获得计算结果为:" + promise.get());

//        // 异步获取promise结果
//        promise.addListener(new GenericFutureListener<Future<? super Integer>>() {
//            @Override
//            public void operationComplete(Future<? super Integer> future) throws Exception {
//                System.out.println(Thread.currentThread().getName() + "等待计算结果");
//                System.out.println(Thread.currentThread().getName() + "获得计算结果为:" + promise.get());
//            }
//        });
    }
}
